package com.whc.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whc.common.utils.PageUtils;
import com.whc.common.utils.Query;
import com.whc.gulimall.product.dao.BrandDao;
import com.whc.gulimall.product.dao.CategoryBrandRelationDao;
import com.whc.gulimall.product.entity.BrandEntity;
import com.whc.gulimall.product.entity.CategoryBrandRelationEntity;
import com.whc.gulimall.product.service.BrandService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;


/**
 * @author angaoen
 */
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    /**
     * 品牌分类关联 Dao
     */
    @Resource
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }
        IPage<BrandEntity> page = this.page(new Query<BrandEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    /**
     * 更新品牌状态
     *
     * @param brandId    品牌id
     * @param showStatus 状态
     */
    @Override
    public void updateStatus(Long brandId, Integer showStatus) {
        baseMapper.updateStatus(brandId, showStatus);
    }

    /**
     * 更新品牌属性及关联表
     *
     * @param brand 品牌表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCascade(BrandEntity brand) {
        // 通过id更新品牌属性
        baseMapper.updateById(brand);
        // 更新关联表
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setBrandId(brand.getBrandId());
        categoryBrandRelationEntity.setBrandName(brand.getName());
        categoryBrandRelationDao.update(categoryBrandRelationEntity, new UpdateWrapper<CategoryBrandRelationEntity>()
                .eq("brand_id", categoryBrandRelationEntity.getBrandId()));
        // TODO:更新其他关联表
    }

}
